<?php


namespace app\backstage\controller;


use app\backstage\logic\PopupLogic;
use app\backstage\logic\RechargeLogic;
use app\common\model\PopupApp;
use app\common\model\RechargeActivity;
use think\Controller;
use think\Db;
use think\db\Expression;

class Popup extends Controller
{

    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    protected $logic;

    public function __construct(PopupLogic $logic = null)
    {
        $this->logic = $logic;
        parent::__construct();
    }

    /**
     * 弹窗列表
     * @return mixed|\think\response\Json
     * @Author: whh
     */
    public function popList()
    {
        $user = request()->_user;
        $role = request()->_role;
        if ($role->alias == 'channel') {
            return errJson('角色异常');
        }
        if (request()->isAjax()) {
            $name = input('name');
            $channel_id = input('channel_id');
            $quick_id = input('quick_id');
            $type = input('type');
            $order = input('order');
            $page = input('page', 1);
            $limit = input('limit', 10);
            $orderBy = $order ? $order . ",id desc" : 'id desc';
            if ($role->alias == 'agent') {
                $where[] = ['manager_id', '=', $user->id];
            } else {
                $where[] = ['manager_id', '=', 0];
            }
            if ($name != '') {
                $where[] = ['name', 'like', "%{$name}%"];
            }
            $ins = '';
            if ($channel_id != '') {
                $ins = "FIND_IN_SET({$channel_id},channels)";
            }
            if ($type != '') {
                $where[] = ['type', '=', $type];
            }
            $ins2 = '';
            if ($quick_id != '') {
                $ins2 = "FIND_IN_SET({$quick_id},quick_apps)";
            }
            $query = $list = \app\common\model\Popup::where($where);
            if ($ins) {
                $query = $query->whereRaw($ins);
            }
            if ($ins2) {
                $query = $query->whereRaw($ins2);
            }
            $count = $query->count();
            $list = $query->order($orderBy)->page($page, $limit)->select();
            return sucJson($list, $count);
        }

        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        $this->assign('role',$role);
        return $this->fetch();
    }

    /**
     * 删除弹窗
     * @throws \Exception
     * @Author: whh
     */
    public function delPop()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.delPop');
        if (true !== $result) {
            $this->error($result);
        }
        $role = request()->_role;
        if ($role->alias == 'channel') {
            return errJson('角色异常');
        }
        $id = input('id');
        $user = request()->_user;
        $where[] = ['id', '=', $id];
        $role = request()->_role;
        $uid = $role->alias == 'agent' ? $user->id : 0;
        $where[] = ['manager_id', '=', $uid];
        \app\common\model\Popup::where($where)->delete();
        $this->success();
    }

    /**
     * 修改弹窗
     * @return mixed|\think\response\Json
     * @Author: whh
     */
    public function editPop()
    {
        $id = input('id');
        $user = request()->_user;
        $role = request()->_role;
        $where[] = ['id', '=', $id];

        if ($role->alias == 'channel') {
            return errJson('角色异常');
        }
        $uid = $role->alias == 'agent' ? $user->id : 0;
        $where[] = ['manager_id', '=', $uid];
        $info = \app\common\model\Popup::where($where)->find();
        if (!$info) {
            $this->error('弹窗不存在');
        }
        if (request()->isAjax()) {
            $params = request()->param();
            if ($role->alias == 'agent') {
                $valStr = 'agentEditPop';
            } else {
                $valStr = 'adminEditPop';
            }
            $result = $this->validate($params, 'app\backstage\validate\PopupValidate.'.$valStr);
            if (true !== $result) {
                $this->error($result);
            }
            $type = input('type');
            if ($type == 1) {
                if (!isset($params['table_novel_id']) || !$params['table_novel_id']) {
                    $this->error('请设置推广书籍');
                }
                $params['novels'] = $params['table_novel_id'];
            } elseif ($type == 2) {
                $activity_id = input('activity_id');
                $activity = RechargeActivity::get($activity_id);
                if (!$activity) {
                    $this->error('请选择推广活动');
                }
                $pic = input('pic');
                if (!$pic) {
                    $params['pic'] = $activity->pop_img;
                }
            } elseif ($type == 3) {
                $jump_url = input('jump_url');
                if (!$jump_url) {
                    $this->error('请输入跳转链接');
                }
                $pic = input('pic');
                if (!$pic) {
                    $this->error('请上传弹窗图片');
                }
            }
            if ($params['register_type'] == 1 && !$params['register_start'] && !$params['register_end']) {
                $this->error('请设置注册时间范围');
            }
            return $this->logic->setPop($params, $id);
        }
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);

        $order = '';
        if ($info->novels) {
            $order = new Expression('field(id,' . $info->novels . ')');
        }
        $novels = \app\common\model\Novel::field("id,title,scale,in_shelf,freq_id,class_id")->where('id', 'in', $info->novels)->with(['freq', 'novel_class'])->order($order)->select();
        $this->assign('novels', $novels);
        $this->assign('info', $info);

        $role_id = Db::table('cms_manager_role')->where('alias','=','agent')->value('id');
        $agents = Db::table('cms_manager_user')->where('role_id','=',$role_id)->field('id,account')->select();
        $this->assign('agents', $agents);
        $allActivity = RechargeLogic::allActivity();
        $this->assign('allActivity', $allActivity);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 添加弹窗
     * @return mixed|\think\response\Json
     * @Author: whh
     */
    public function addPop()
    {
        $user = request()->_user;
        $role = request()->_role;
        if ($role->alias == 'channel') {
            return errJson('角色异常');
        }
        if (request()->isAjax()) {
            $params = request()->param();

            if ($role->alias == 'agent') {
                $valStr = 'agentAddPop';
            } else {
                $valStr = 'adminAddPop';
            }
            $result = $this->validate($params, 'app\backstage\validate\PopupValidate.' . $valStr);
            if (true !== $result) {
                $this->error($result);
            }
            $type = input('type');
            if ($type == 1) {
                if (!isset($params['table_novel_id']) || !$params['table_novel_id']) {
                    $this->error('请设置推广书籍');
                }
                $params['novels'] = $params['table_novel_id'];
            } elseif ($type == 2) {
                $activity_id = input('activity_id');
                $activity = RechargeActivity::get($activity_id);
                if (!$activity) {
                    $this->error('请选择推广活动');
                }
                $pic = input('pic');
                if (!$pic) {
                    $params['pic'] = $activity->pop_img;
                }
            } elseif ($type == 3) {
                $jump_url = input('jump_url');
                if (!$jump_url) {
                    $this->error('请输入跳转链接');
                }
                $pic = input('pic');
                if (!$pic) {
                    $this->error('请上传弹窗图片');
                }
            }
            if ($params['register_type'] == 1 && !$params['register_start'] && !$params['register_end']) {
                $this->error('请设置注册时间范围');
            }
            if ($params['date_type'] == 5 && !$params['start_end']){
                $this->error('请设置自定义日期范围');
            }
            return $this->logic->setPop($params);
        }
        $role_id = Db::table('cms_manager_role')->where('alias','=','agent')->value('id');
        $agents = Db::table('cms_manager_user')->where('role_id','=',$role_id)->field('id,account')->select();
        $this->assign('agents', $agents);
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        $allActivity = RechargeLogic::allActivity();
        $this->assign('allActivity', $allActivity);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 设置权重
     * @Author: whh
     */
    public function setPopWgt()
    {
        $id = input('id');
        $wgt = input('wgt');
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.setPopWgt');
        if (true !== $result) {
            $this->error($result);
        }
        $user = request()->_user;
        $role = request()->_role;
        $uid = $role->alias == 'agent' ? $user->id : 0;
        $where[] = ['id', '=', $id];
        $where[] = ['manager_id', '=', $uid];
        \app\common\model\Popup::where($where)->setField('wgt', $wgt);
        $this->success();
    }

    /**
     * 设置app权重
     */
    public function setAppPopWgt()
    {
        $id = input('id');
        $wgt = input('wgt');
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.setPopWgt');
        if (true !== $result) {
            $this->error($result);
        }
        $where[] = ['id', '=', $id];
        PopupApp::where($where)->setField('wgt', $wgt);
        $this->success();
    }

    /**
     * 下载弹窗
     * @return mixed|\think\response\Json
     */
    public function appPopups()
    {
        if (request()->isAjax()) {
            $name = input('name');
            $quick_id = input('quick_id');
            $order = input('order');
            $page = input('page', 1);
            $limit = input('limit', 10);
            $orderBy = $order ? $order . ",id desc" : 'id desc';
            $where = [];
            if ($name != '') {
                $where[] = ['name', 'like', "%{$name}%"];
            }
            $ins = '';
            if ($quick_id != '') {
                $ins = "FIND_IN_SET({$quick_id},quick_apps)";
            }
            $query = $list = PopupApp::where($where);
            if ($ins) {
                $query = $query->whereRaw($ins);
            }
            $count = $query->count();
            $list = $query->order($orderBy)->page($page, $limit)->select();
            return sucJson($list, $count);
        }
        $user = request()->_user;
        $qas = getMyQas($user);
        $this->assign('qas', $qas);
        return $this->fetch();
    }

    /**
     * 添加下载弹窗
     * @return mixed|\think\response\Json
     */
    public function addAppPop()
    {
        $user = request()->_user;
        $qas = getMyQas($user);
        $this->assign('qas', $qas);
        if (request()->isAjax()) {
            $params = request()->param();
            $result = $this->validate($params, 'app\backstage\validate\PopupValidate.addAppPop');
            if (true !== $result) {
                $this->error($result);
            }
            if ($params['register_type'] == 1 && !$params['register_start'] && !$params['register_end']) {
                $this->error('请设置注册时间范围');
            }
            return $this->logic->setAppPop($params);
        }
        return $this->fetch();
    }


    /**
     * 编辑下载弹窗
     * @return mixed|\think\response\Json
     */
    public function editAppPop()
    {
        $id = input('id');
        $user = request()->_user;
        $where[] = ['id', '=', $id];
        $info = PopupApp::where($where)->find();
        if (!$info) {
            $this->error('弹窗不存在');
        }
        if (request()->isAjax()) {
            $params = request()->param();
            $result = $this->validate($params, 'app\backstage\validate\PopupValidate.editAppPop');
            if (true !== $result) {
                $this->error($result);
            }
            if ($params['register_type'] == 1 && !$params['register_start'] && !$params['register_end']) {
                $this->error('请设置注册时间范围');
            }
            return $this->logic->setAppPop($params, $id);
        }
        $qas = getMyQas($user);
        $this->assign('qas', $qas);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除弹窗
     * @throws \Exception
     * @Author: whh
     */
    public function delAppPop()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.delPop');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $where[] = ['id', '=', $id];
        PopupApp::where($where)->delete();
        $this->success();
    }

    /**
     * 设置app弹窗开关
     * @Author: whh
     */
    public function setAppPopStatus()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.setAppPopStatus');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $status = input('status');
        $pop = PopupApp::get($id);
        if (!$pop) {
            $this->error('弹窗不存在');
        }
        $pop->status = $status;
        $pop->save();
        $this->success();
    }

    /**
     * 设置app弹窗开关
     * @Author: whh
     */
    public function setPopStatus()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.setAppPopStatus');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $status = input('status');
        $user = request()->_user;
        $role = request()->_role;
        $uid = $role->alias == 'agent' ? $user->id : 0;
        $where[] = ['id', '=', $id];
        $where[] = ['manager_id', '=', $uid];
        $pop = \app\common\model\Popup::where($where)->find();
        if (!$pop) {
            $this->error('弹窗不存在');
        }
        $pop->status = $status;
        $pop->save();
        $this->success();
    }

    /**
     * 设置置顶
     */
    public function setPopTopped()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\PopupValidate.setPopTopped');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $topped = input('topped');
        $user = request()->_user;
        $role = request()->_role;
        $uid = $role->alias == 'agent' ? $user->id : 0;
        $where[] = ['id', '=', $id];
        $where[] = ['manager_id', '=', $uid];
        $pop = \app\common\model\Popup::where($where)->find();
        if (!$pop) {
            $this->error('弹窗不存在');
        }
        $pop->topped = $topped;
        $pop->save();
        $this->success();
    }
}